<?php

declare(strict_types=1);

namespace RX\Core;

use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;
use RX\Enums\CommonEnum;
use RX\Exception\BizException;
use RX\Helpers\LoggerHelper;
use RX\Traits\RequestTrait;
use Throwable;

abstract class CoreController extends Controller
{
    use RequestTrait;

    protected function getHost()
    {
        $uri    = $this->request()->getUri();
        $scheme = $uri->getScheme();
        return $scheme . '://' . $uri->getHost();
    }

    protected function getParams(): array
    {
        $request = $this->request();
        $params  = $this->getRequestParams($request);
        return array_filter($params, function ($val) {
            return is_string($val) ? trim($val) !== "" : true;
        });
    }


    protected function success(string $msg, $data = null): bool
    {
        return $this->result(CommonEnum::SUCCESS, $msg, $data);
    }

    protected function error($code, string $msg, $data = null): bool
    {
        return $this->result($code, $msg, $data);
    }


    protected function result($code, string $msg, $data = null): bool
    {
        $response = $this->response();
        if (!$response->isEndResponse()) {
            $result = [
                'code' => $code,
                'msg'  => $msg,
            ];
            if (!is_null($data) || (is_array($data) && !empty($data))) {
                $result['data'] = $data;
            }
            $response->withStatus(Status::CODE_OK);
            $response->withHeader('Content-type', 'application/json;charset=utf-8');
            $response->write(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $response->end();
        }
        return true;
    }

    public function download($param)
    {
        $filePath = $param['path'] ?? '';
        $fileName = $param['name'] ?? '';
        $response = $this->response();
        if (empty($filePath) || !file_exists($filePath)) {
            throw new BizException(CommonEnum::class, CommonEnum::SERVER_NOT_FOUND);
        }
        $response->withHeader('Access-Control-Allow-Origin', '*');
        $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->withHeader('Access-Control-Allow-Credentials', 'true');
        $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');

        $fileName       = $fileName ?: pathinfo($filePath, PATHINFO_FILENAME);
        $fileExtNameSub = pathinfo($filePath, PATHINFO_EXTENSION);
        $fileName       = $fileName . '.' . $fileExtNameSub;
        $response->withHeader('Content-type', 'application/octet-stream');
        $response->withHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT');
        $response->withHeader('Content-Transfer-Encoding', 'binary');
        $response->withHeader('Content-length', filesize($filePath));
        $response->withHeader('Content-Disposition', 'filename="' . $fileName . '"');
        $response->withStatus(200);
        $response->write(file_get_contents($filePath));
        $response->end();
        return true;
    }
}
